package org.example.likou150.tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

// https://leetcode.cn/problems/average-of-levels-in-binary-tree/?envType=study-plan-v2&envId=top-interview-150
public class AverageOfLevels {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(2147483647);
        treeNode.left = new TreeNode(2147483647);
        treeNode.right = new TreeNode(2147483647);

        AverageOfLevels averageOfLevels = new AverageOfLevels();
        averageOfLevels.averageOfLevels(treeNode);
    }

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        while(!queue.isEmpty()){
            double total = 0;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                total+=treeNode.val;
                if(i == size-1)  list.add(total/size);
                if(treeNode.left!=null) queue.add(treeNode.left);
                if(treeNode.right!=null) queue.add(treeNode.right);
            }
        }
        return list;
    }


    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
